<?php
namespace app\auth\logic;

use think\Db;

class AuthEncrypt
{

    /**
     * length of authKey
     * @var integer
     */
    protected static $length = 8;
    /**
     * model of encrypt
     * @var string
     */
    protected static $cipher = 'AES-256-CBC';
    /**
     * model of encrypt Arr
     * @var [type]
     */
    protected static $allowedCiphers = [
        'AES-128-CBC' => [16, 16],
        'AES-192-CBC' => [16, 24],
        'AES-256-CBC' => [16, 32],
    ];

    /**
     * 加密 uid auth_key
     * @param  int    $uid     用户ID
     * @param  stirng $authKey 授权key
     * @return string
     */
    public static function encrypt($uid, $authKey = null)
    {
        if (null === $authKey) {
            $authKey = static::generateAuthKey($uid);
        }
        $data = $uid . '|' . $authKey;
        $key  = openssl_random_pseudo_bytes(self::$allowedCiphers[self::$cipher][1]);
        $iv   = openssl_random_pseudo_bytes(self::$allowedCiphers[self::$cipher][0]);
        return  base64_encode(openssl_encrypt($data, self::cipher, $key, OPENSSL_RAW_DATA, $iv));
    }
    /**
     * 解密身份 token
     * @param  string $data token
     * @return array       ['uid'=>'', 'auth_key'=>'']
     */
    public static function decrypt($data)
    {
        $key    = openssl_random_pseudo_bytes(self::$allowedCiphers[self::$cipher][1]);
        $iv     = openssl_random_pseudo_bytes(self::$allowedCiphers[self::$cipher][0]);
        $string = openssl_decrypt(base64_decode($data), self::$cipher, $key, OPENSSL_RAW_DATA, $iv);
        $strArr = explode('|', $string);
        return ['uid'=>$strArr[0], 'auth_key'=>$strArr[1]];
    }

    /**
     * 生成 auth_key 写入到数据库
     * @param  int    $uid 用户 ID
     * @return string 生成的 auth_key
     */
    public static function generateAuthKey($uid)
    {
        // 生成 auth_key
        $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $authKey = '';
        for ($i=0; $i<self::$length; $i++) {
            $authKey .= substr($string, rand(0,strlen($string) -1), 1);
        }
        // 写入数据库
        (new \app\auth\model\User) ->updateAuthKey($uid, $authKey);
        return $authKey;
    }
}